<template>
  <halo-dialog v-model:visible="visible" @cancel="close">
    <div class="btn-card" v-if="!direct">
      <button class="halo-close-btn" @click="close">
        <i class="iconfont icon-close"></i>
      </button>
      <div class="btn-title">请验证手机号</div>
      <div class="phone">{{ phone }}</div>
      <div class="submit-btn" :style="{ backgroundColor: color }" @click="toFetchCode">
        获取验证码
      </div>
    </div>
    <code-card
      v-else
      :color="color"
      :phone="phone"
      @close="close"
      @success="success"
      @send="toFetchCode"
    />
  </halo-dialog>
</template>

<script>
import { toast } from '@/utils/feedback';
import { fetchCode } from '@/api/supplier';
import HaloDialog from '@/common/halo-dialog';

import CodeCard from './code-card';

export default {
  components: {
    HaloDialog,
    CodeCard,
  },
  data() {
    return {
      phone: '',
      color: '#2978ff',
      visible: false,
      direct: false,
      fetchCode: fetchCode,
      callback: () => {},
      fail: () => {},
    };
  },
  methods: {
    async show(
      { phone, color, fetchCode: newFetchCode } = {},
      direct = false,
      callback = () => {},
      fail = () => {}
    ) {
      this.color = color || '#2978ff';
      phone && (this.phone = phone);
      newFetchCode && (this.fetchCode = newFetchCode);
      this.direct = direct;
      this.callback = callback;
      this.fail = fail;
      if (direct) {
        await this.toFetchCode();
      }
      this.visible = true;
    },
    async toFetchCode() {
      const { phone } = this;
      if (!/^1\d{10}$/.test(phone)) return toast('请正确输入手机号');
      this.direct = true;
      const now = new Date().getTime();
      if (now - 60 * 1000 > (window.lastfetchCodeTime || 0)) {
        window.lastfetchCodeTime = now;
        await this.fetchCode({ phone });
      }
    },
    close() {
      this.visible = false;
      this.fail('取消验证码弹窗');
    },
    success(code) {
      this.visible = false;
      this.callback(code);
    },
  },
};
</script>

<style lang="less" scoped>
.btn-card {
  width: 610px;
  background: #ffffff;
  border-radius: 12px;
  position: relative;
  text-align: center;
  padding-bottom: 40px;
  .btn-title {
    font-weight: bold;
    font-size: 34px;
    color: #323038;
    line-height: 48px;
    padding-top: 40px;
  }
  .phone {
    padding: 50px 0;
    font-size: 40px;
    color: #323038;
  }
}
.halo-close-btn {
  position: absolute;
  top: 0;
  right: 0;
  transform-origin: top right;
  transform: scale(0.9);
}
.submit-btn {
  width: 530px;
  height: 92px;
  background: #2978ff;
  border-radius: 8px;
  margin: 0 auto;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 32px;
  color: #ffffff;
  &:active {
    opacity: 0.9;
  }
}
</style>